package cn.lu.intercept;

import cn.lu.pojo.User;
import cn.lu.utils.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

public class CrossingFilter implements Filter {

    private JedisPool jedisPool;

    private boolean isCross = false;

    @Override
    public void destroy() {
        isCross = false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (isCross) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            System.out.print(null == httpServletRequest.getHeader("Origin") ? "手动请求" : httpServletRequest.getHeader("Origin"));
            System.out.println(" ==> 拦截请求: " + httpServletRequest.getServletPath());
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            //httpServletResponse.setHeader("Access-Control-Allow-Methods", "*"); // 表示所有请求都有效
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE,PUT");
            httpServletResponse.setHeader("Access-Control-Max-Age", "0");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("XDomainRequestAllowed", "1");
            String token = request.getHeader("token");
            Jedis jedis = jedisPool.getResource();
            boolean visit = request.getServletPath().equals("/user/login");
            if (visit) {
                if (token==null){
                    chain.doFilter(request, response);
                }else{
                    if (jedis.ttl(token) > 0) {
                        jedis.expire(token, 600);
                        PrintWriter out = response.getWriter();
                        response.setContentType("json/text;charset=utf-8");
                        out.write(JSON.toJSONString(new Result().fail("现在是登录状态")));
                    } else {
                        chain.doFilter(request, response);
                    }
                }
            } else {
                if (token != null) {
                    if (jedis.ttl(token) > 0) {
                        String userId = request.getHeader("userId");
                        if (userId!=null && JSONObject.parseObject(jedis.get(token), User.class).getId()==Integer.parseInt(userId)) {
                            jedis.expire(token, 600);
                            chain.doFilter(request, response);
                        } else {
                            PrintWriter out = response.getWriter();
                            response.setContentType("json/text;charset=utf-8");
                            out.write(JSON.toJSONString(new Result().fail("信息异常")));
                        }
                    } else {
                        PrintWriter out = response.getWriter();
                        response.setContentType("json/text;charset=utf-8");
                        out.write(JSON.toJSONString(new Result().fail("访问异常")));
                    }
                } else {
                    PrintWriter out = response.getWriter();
                    response.setContentType("json/text;charset=utf-8");
                    out.write(JSON.toJSONString(new Result().fail("请先登录")));
                }
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Properties properties = new Properties();
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("redis.properties");
        try {
            properties.load(resourceAsStream);
            String host = properties.getProperty("redis.host");
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            Integer port = Integer.parseInt(properties.getProperty("redis.port"));
            String password = properties.getProperty("redis.password");
            jedisPool = new JedisPool(poolConfig, host, port, 1000, password);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String isCrossStr = filterConfig.getInitParameter("IsCross");
        isCross = isCrossStr.equals("true") ? true : false;
        System.out.println("跨域开启状态：" + isCrossStr);
    }
}